# leetcode 145 二叉树的后序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        left = self.postorderTraversal(root.left)
        right = self.postorderTraversal(root.right)
        return left + right + [root.val]

# 非递归实现
class Solution:
    def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack = []
        result = []
        stack.append(root)
        while len(stack) > 0:
            node = stack.pop()
            if node is not None:
                result.append(node.val)
                # 先加入左，再加入右，这样数组顺序变为中右左
                # 最后将结果数组进行反转，顺序即可变为左右中，即后序遍历
                stack.append(node.left)
                stack.append(node.right)
        return result[::-1]
